var index = 1;
define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'echarts'], function ($, undefined, Backend, Table, Form, Echarts) {

    var Controller = {
        source: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'facrm/analysis/achievement/source',
                    add_url: '',
                    edit_url: '',
                    del_url: '',
                    multi_url: '',
                    table: '',
                }
            });

            var table = $("#table");

            //在普通搜索渲染后
            table.on('post-common-search.bs.table', function (event, table) {
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                searchFormVisible:true, //打开搜索
                search: false,
                columns: [
                    [
                        {field: 'index', title: __('序号'), operate: false},

                        {
                            field: 'source_id', title: __('来源'), formatter: function (v, r, index) {
                                return sourceList[v];
                            }, searchList: sourceList
                        },
                        {field: 'department_id', title: __(''), visible: false,
                         searchList:Config.groupdata},

                        {field: 'order_admin_id', title: __('员工'), visible: false,addclass: 'selectpage',
                            extend: 'data-source="facrm/common/selectpage/model/admin" data-field="nickname" data-orderBy="id desc"'},
                        {field: 'count', title: __('订单数量'), operate: false},
                        {field: 'money', title: __('订单总额'), operate: false},
                        {field: 'return_money', title: __('已收金额'), operate: false},

                        {field: 'customer_data.collect_count', title: __('客户数'), operate: false},
                        {field: 'customer_data.purchase_count', title: __('成交数'), operate: false},
                        {field: 'customer_data.percentage', title: __('成交率'), operate: false},
                        {
                            field: 'order_time',
                            title: __('下单时间段'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            extend: 'autocomplete="off"',
                            visible:false
                        },

                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

        },
        groups: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'facrm/analysis/achievement/groups',
                    add_url: '',
                    edit_url: '',
                    del_url: '',
                    multi_url: '',
                    table: '',
                }
            });

            var table = $("#table");

            //在普通搜索渲染后
            table.on('post-common-search.bs.table', function (event, table) {
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                pagination: false,
                escape: false,
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {
                            field: 'id',
                            title: '<a href="javascript:;" class="btn btn-success btn-xs btn-toggle"><i class="fa fa-chevron-up"></i></a>',
                            operate: false,
                            cellStyle: function () {return {css: {"width": "50px"}}},
                            formatter: Controller.api.formatter.subnode
                        },
                        {field: 'name', title: __('团队'), align: 'left', operate: false},

                        {field: 'contract.count', title: __('订单数量'), operate: false},
                        {field: 'contract.money', title: __('订单总额'), operate: false},
                        {field: 'contract.return_money', title: __('已收金额'), operate: false},

                        {field: 'customer_data.collect_count', title: __('分配数'), operate: false},
                        {field: 'customer_data.purchase_count', title: __('分配成交数'), operate: false},
                        {field: 'customer_data.percentage', title: __('分配成交率'), operate: false},
                        {
                            field: 'order_time',
                            title: __('下单时间段'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            extend: 'autocomplete="off"',
                            visible:false
                        },,


                    ]
                ],
                search: false,
                searchFormVisible:true, //打开搜索
            });

            //当内容渲染完成后
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                //默认隐藏所有子节点
                //$("a.btn[data-id][data-pid][data-pid!=0]").closest("tr").hide();
                //$(".btn-node-sub.disabled[data-pid!=0]").closest("tr").hide();

                //显示隐藏子节点
                $(".btn-node-sub").off("click").on("click", function (e) {
                    var status = $(this).data("shown") || $("a.btn[data-pid='" + $(this).data("id") + "']:visible").size() > 0 ? true : false;
                    $("a.btn[data-pid='" + $(this).data("id") + "']").each(function () {
                        $(this).closest("tr").toggle(!status);
                        if (!$(this).hasClass("disabled")) {
                            $(this).trigger("click");
                        }
                    });
                    $(this).data("shown", !status);
                    return false;
                });

            });
            //展开隐藏一级
            $(document.body).on("click", ".btn-toggle", function (e) {
                $("a.btn[data-id][data-pid][data-pid!=0].disabled").closest("tr").hide();
                var that = this;
                var show = $("i", that).hasClass("fa-chevron-down");
                $("i", that).toggleClass("fa-chevron-down", !show);
                $("i", that).toggleClass("fa-chevron-up", show);
                $("a.btn[data-id][data-pid][data-pid!=0]").closest("tr").toggle(show);
                $(".btn-node-sub[data-pid=0]").data("shown", show);
            });
            //展开隐藏全部
            $(document.body).on("click", ".btn-toggle-all", function (e) {
                var that = this;
                var show = $("i", that).hasClass("fa-plus");
                $("i", that).toggleClass("fa-plus", !show);
                $("i", that).toggleClass("fa-minus", show);
                $(".btn-node-sub.disabled[data-pid!=0]").closest("tr").toggle(show);
                $(".btn-node-sub[data-pid!=0]").data("shown", show);
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            require.config({
                    paths: {
                        'Gzyechart': '../addons/facrm/js/gzyechart',
                    }
                }
            );
            require(['Gzyechart'], function () {
                Form.api.bindevent($("form[role=form]"));
                // 基于准备好的dom，初始化健康表格数据
                Gzyechart.echart.loadEchart("achievement", Echartdata.achievement.date, Echartdata.achievement.data);
                Gzyechart.echart.initButton();
                $(document).on("change", "#c-owner_user_id", function () {
                    var owner_user_id = $(this).val();
                    var datetimerange = $(this).parent().parent().find(".datetimerange");
                    var url = datetimerange.data('url');
                    if (url.indexOf("owner_user_id") != -1) {
                        url = Controller.api.replaceParamVal(url, "owner_user_id", owner_user_id);
                    } else {
                        url = url + "&owner_user_id=" + owner_user_id;
                    }
                    datetimerange.data('url', url);
                });

                $(document).on("change", "#c-group_id", function () {

                    var group_id = $(this).val();
                    var datetimerange = $(this).parent().parent().parent().find(".datetimerange");
                    var url = datetimerange.data('url');
                    if (url.indexOf("group_id") != -1) {
                        url = Controller.api.replaceParamVal(url, "group_id", group_id);
                    } else {
                        url = url + "&group_id=" + group_id;
                    }
                    datetimerange.data('url', url);
                });

            });


        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {
                title: function (value, row, index) {
                    return !row.ismenu || row.status == 'hidden' ? "<span class='text-muted'>" + value + "</span>" : value;
                },
                name: function (value, row, index) {
                    return !row.ismenu || row.status == 'hidden' ? "<span class='text-muted'>" + value + "</span>" : value;
                },
                icon: function (value, row, index) {
                    return '<span class="' + (!row.ismenu || row.status == 'hidden' ? 'text-muted' : '') + '"><i class="' + value + '"></i></span>';
                },
                subnode: function (value, row, index) {
                    return '<a href="javascript:;" data-toggle="tooltip" title="' + __('Toggle sub menu') + '" data-id="' + row.id + '" data-pid="' + row.pid + '" class="btn btn-xs '
                        + (row.haschild == 1 || row.ismenu == 1 ? 'btn-success' : 'btn-default disabled') + ' btn-node-sub"><i class="fa fa-' + (row.haschild == 1 || row.ismenu == 1 ? 'sitemap' : 'list') + '"></i></a>';
                }
            },

            //替换指定传入参数的值,paramName为参数,replaceWith为新值
            replaceParamVal: function (oUrl, paramName, replaceWith) {
                var re = eval('/(' + paramName + '=)([^&]*)/gi');
                return oUrl.replace(re, paramName + '=' + replaceWith);
            },
            loadEchart: function (echartname, data) {

                option = {
                    title: {
                        text: '',
                        subtext: '',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: '{c}%'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                    },
                    series: [
                        {
                            name: '跟进方式',
                            type: 'pie',
                            radius: '70%',
                            data: data,
                            label: {
                                formatter: '{b}: {@name} ({d}%)'
                            },
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ]
                };
                var record_type = Echarts.init(document.getElementById(echartname));
                record_type.setOption(option);
            },

        }
    };
    return Controller;
});


